<template>
  <div class="home">
    <van-nav-bar
      title="共同居住人"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- <img src="../../assets/images/rlzzbb.png" /> -->

    <van-form validate-first ref="formDataRef" @submit="onSubmit">
      <van-field
        v-model="name"
        name="选择学生"
        label="选择学生"
        placeholder="选择学生"
        @focus="showCode = true"
        :rules="rules.schoolDistrictName"
      />
      <van-popup v-model="showCode" round position="bottom">
        <van-picker
          show-toolbar
          :columns="studentColumns"
          value-key="name"
          @cancel="showCode = false"
          @confirm="val => onCodeConfirm(val)"
        />
      </van-popup>
      <van-cell-group
        v-for="(item, index) in addManForm.formData"
        :model="addManForm"
        :key="index"
        inset
        title="共同居住人"
      >
        <van-cell value="删除共同居住人">
          <template #right-icon>
            <van-icon
              @click="removeResident(index, item)"
              name="cross"
              class="search-icon"
            />
          </template>
        </van-cell>

        <van-field
          v-model="addManForm.formData[index].name"
          required
          label="同住人姓名"
          placeholder="同住人姓名"
          :rules="rules.name"
        />

        <van-field
          v-model="addManForm.formData[index].mobile"
          required
          label="同住人手机号码"
          placeholder="同住人手机号码"
          :rules="rules.mobile"
        />
        <van-field
          v-model="addManForm.formData[index].cardno"
          required
          label="同住人身份证号"
          placeholder="同住人身份证号"
          :rules="rules.cardno"
          maxlength="18"
        />
        <van-field
          v-model="addManForm.formData[index].addressProvince"
          readonly
          required
          label="居住地"
          placeholder="点击选择省市区"
          @click="
            showArea2 = true
            selectedIndex = index
          "
          :rules="[{ required: true, message: '请选择正确内容' }]"
        >
        </van-field>
        <van-popup v-model:show="showArea2" position="bottom">
          <van-area
            value="210200"
            :area-list="areaList"
            @confirm="val => enAreaConfirm(index, val)"
            @cancel="showArea2 = false"
          >
          </van-area>
        </van-popup>
        <van-field
          label="详细地址"
          required
          v-model="addManForm.formData[index].addressInfo"
          name="pattern"
          placeholder="请输入详细地址"
        />
        <van-field
          v-model="addManForm.formData[index].relation"
          label="同住人身份"
          placeholder="同住人身份"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button @click="pushResidentList()" round block type="info">
          <!-- native-type="submit" -->
          <van-icon name="plus" /> 追加共同居住人
        </van-button>
      </div>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          保存
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import {
  addCohabitantInfo,
  getAllCohabitantByUserId,
  deleteCohabitant,
  getUserByFamilyId
} from '@/api/student/register'
import { Toast, Dialog } from 'vant'
import { areaList } from '@vant/area-data'

export default {
  data() {
    return {
      selectedIndex: '',
      areaList,
      showArea2: false,
      showCode: false,
      name: '',
      userInfoId: '',
      addManForm: {
        userInfoId: this.$route.query.sysUserId, // 用户关联主键id
        formData: [
          {
            name: '', // 同住人姓名
            relation: '', // 同住人身份
            mobile: '', // 同住人手机号
            cardno: '', // 同住人身份证号
            addressProvince: '',
            addressInfo: '' // 详细地址
          }
        ]
      },
      studentColumns: [],
      rules: {
        name: [
          {
            required: true,
            message: '同居人姓名',
            trigger: ['blur', 'change']
          }
        ],
        relation: [
          {
            required: true,
            message: '同住人身份',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            required: true,
            message: '同住人手机号',
            trigger: ['blur', 'change']
          }
        ],
        cardno: [
          {
            required: true,
            message: '同住人身份证号',
            trigger: ['blur', 'change']
          }
        ]
      },
      residentList: []
    }
  },
  mounted() {
    // this.formData.code = this.$route.query.code
    // for (let i in this.formData) {
    //   this.formData[i] = ''
    // }
    this.getUserByFamilyListById()
    this.getInitResident()
    // this.addManForm.userInfoId = this.$route.query.sysUserId
  },
  methods: {
    onCodeConfirm(value) {
      this.userInfoId = value.id
      this.name = value.name
      // this.addManForm.formData.userId = value.id
      // this.addManForm.formData.name = value.name
      getAllCohabitantByUserId(value.id).then(res => {
        if (res.data.errcode === 0) {
          this.addManForm.formData = res.data.data
          console.log(this.addManForm.formData)
        } else {
          Toast.fail(res.data.msg)
        }
      })
      this.showCode = false
    },
    getUserByFamilyListById() {
      getUserByFamilyId(this.$route.query.familyId).then(res => {
        if (res.data.errcode === 0) {
          this.studentColumns = res.data.data
          console.log(this.studentColumns)
        } else {
          Toast.fail(res.data.msg)
        }
      })
    },

    pushResidentList() {
      this.addManForm.formData.push({
        name: '',
        relation: '',
        mobile: '',
        cardno: ''
      })
    },
    removeResident(index, item) {
      if (item.id == null) {
        // Toast.fail('不能继续删除')
        // return
        this.addManForm.formData.splice(index, 1)
        return
      }
      deleteCohabitant(item.id).then(res => {
        if (res.data.errcode === 0) {
          this.addManForm.formData.splice(index, 1)
          // this.$router.push({ name: 'student-menu', query: { id: id } })
          Dialog.alert({
            message: '提交成功',
            showCancelButton: false,
            showConfirmButton: false
          }).then(() => {})
          const TIMEOUT = setTimeout(() => {
            Dialog.close()
            clearTimeout(TIMEOUT)
          }, 2000)
        } else {
          Toast.fail(res.data.msg)
        }
      })
    },
    getConfirm(value) {
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.bithday = yy + '-' + mm + '-' + dd
      this.showDate = false
    },
    onAreaConfirm(value) {
      this.showArea = false
      this.formData.start_addr_list = value
        .filter(item => !!item)
        .map(item => item.name)
        .join('/')
    },

    enAreaConfirm(index, value) {
      console.log('居住地===', index)
      this.showArea2 = false
      let data = value
        .filter(item => !!item)
        .map(item => item.name)
        .join('/')
      this.addManForm.formData[this.selectedIndex].addressProvince = data
    },
    getInitResident() {
      // if (this.addManForm.userInfoId == null) {
      //   return Toast.fail('登录状态已失效')
      // }
      // getAllCohabitantByUserId(this.$route.query.sysUserId).then((res) => {
      //   if (res.data.errcode === 0) {
      //     this.addManForm.formData = res.data.data
      //     console.log(this.addManForm.formData)
      //   } else {
      //     Toast.fail(res.data.msg)
      //   }
      // })
    },
    goDlConfirm(value) {
      const formatDate = value =>
        `${value.get}/${value.getMonth() + 1}/${value.getDate()}`
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.estimated_arrival_date = yy + '-' + mm + '-' + dd
      this.goDlShow = false
    },

    onSubmit() {
      this.$refs.formDataRef
        .validate()
        .then(() => {
          // 验证通过
          console.log(this.addManForm)
          if (this.addManForm.formData.length == 0) {
            return Toast.fail('目前没有添加数据')
          }
          this.addManForm.userInfoId = this.userInfoId
          addCohabitantInfo(this.addManForm).then(res => {
            // if (this.addManForm.userInfoId == null) {
            //   return Toast.fail('登录状态已失效')
            // }

            if (res.data.errcode === 0) {
              Dialog.alert({
                message: '提交成功',
                showCancelButton: false,
                showConfirmButton: false
              }).then(() => {})
              const TIMEOUT = setTimeout(() => {
                Dialog.close()
                clearTimeout(TIMEOUT)
              }, 2000)
              this.$router.push({
                name: 'student-menu',
                query: { sysUserId: this.$route.query.sysUserId }
              })
            } else {
              Toast.fail(res.data.msg)
            }
          })
        })
        .catch(() => {
          // 验证失败
          // Toast.fail(res.data.msg)
          Toast.fail('验证失败')
        })

      // helpUserInsert(formdata).then((res) => {
      //   Toast.clear()
      //   if (res.data.errcode === 0) {
      //     let id =
      //       this.$route.query.id != null
      //         ? this.$route.query.id
      //         : res.data.data.id
      //     this.$router.push({ name: 'recordQrCode', query: { id: id } })
      //     Dialog.alert({
      //       message: '提交成功',
      //       showCancelButton: false,
      //       showConfirmButton: false,
      //     }).then(() => {})
      //     const TIMEOUT = setTimeout(() => {
      //       Dialog.close()
      //       clearTimeout(TIMEOUT)
      //     }, 2000)
      //     // 提交成功清空数据
      //     for (let i in this.formData) {
      //       this.formData[i] = ''
      //       this.formData.avenue_flow_area = true
      //     }
      //   } else {
      //     Toast.fail(res.data.msg)
      //   }
      // })
    }
  }
}
</script>
<style lang="less" scoped>
.upload-img-5 {
  margin: 5px 0 90px 0;
}
.upload-img-1 {
  margin: 5px 0 15px 0;
}

.home {
  height: 100%;
  background: url('../../assets/images/smtb.jpg') no-repeat;

  img {
    // background: url('../../assets/images/smtb.jpg');
    width: 100%;
  }
  .dialog-container {
    height: 70vh;
    overflow-y: auto;
  }
  .get-area {
    width: 100%;
    padding: 0 0.8rem;
    font-size: 0.747rem;
    color: #fff;
    background-color: #1989fa;
    border: 0.053rem solid #1989fa;
    height: 2.347rem;
    line-height: 2.347rem;
    text-align: center;
    border-radius: 0.107rem;
    cursor: pointer;
    box-sizing: border-box;
    margin-right: 10px;
  }
  /deep/.van-field__label {
    width: 8em;
  }
  /deep/.van-field__error-message {
    text-align: right;
  }
  .title {
    // font-size: 28px;
    text-indent: 20px;
    padding: 50px 0 20px;
  }
  .container {
    width: 90%;
    height: 80vh;
    overflow-y: auto;
    border: 1px solid #adadad;
    margin: auto;
    .item {
      margin: 10px;
    }
  }
}
.up-and-down {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f1f3f4;
  height: 80px;
  color: #333;
}
</style>
